package com.topcheer.common.base.util;

import com.topcheer.common.base.context.BaseContextHandler;

import java.util.Date;

/**
 * @author xutao
 * @Package com.topcheer.common.base.util
 * @Description: ${todo}
 * @date 2020/3/29 21:36
 */
public class EntityUtils {

    public static <T> void setCreateInfo(T entity) {
        Long userId = BaseContextHandler.getUserID();
        String[] fields = {"createUserid",
            "createTime"};
        Object[] values = new Object[] {userId,
            new Date()};
        setValues(entity, fields, values);
    }

    public static <T> void setUpdateInfo(T entity) {
        Long userId = BaseContextHandler.getUserID();
        String[] fields = {"updateUserid",
            "updateTime"};
        Object[] values = new Object[] {userId,
            new Date()};
        setValues(entity, fields, values);
    }

    private static <T> void setValues(T entity, String[] fields, Object[] values) {
        for (int i = 0; i < fields.length; i++) {
            String field = fields[i];
            Object value = values[i];
            if (ReflectionUtil.hasField(entity, field)) {
                ReflectionUtil.setFieldValue(entity, field, value);
            }
        }
    }
}
